package com.ia.aistream.service.operating.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ia.aistream.manager.common.ICommonFileManager;
import com.ia.aistream.manager.dxfcomponent.conf.DrawConf;
import com.ia.aistream.manager.operating.util.visio.PdfToPngUtil;
import com.ia.aistream.mapper.operating.*;
import com.ia.aistream.model.common.entity.CommonFile;
import com.ia.aistream.model.operating.dto.ParagraphTextStyle;
import com.ia.aistream.model.operating.dto.TextInfo;
import com.ia.aistream.model.operating.dto.visio.VueVisioDto;
import com.ia.aistream.model.operating.dto.vue.*;
import com.ia.aistream.model.operating.entity.*;
import com.ia.aistream.service.operating.IDocDocumentService;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XiaoYu
 */
@Service
public class DocDocumentServiceImpl implements IDocDocumentService {

    /** 注入所有Mapper对象 */
    @Autowired
    private DocIndexMapper docIndexMapper;
    @Autowired
    private DocApprovalMapper docApprovalMapper;
    @Autowired
    private DocRevMapper docRevMapper;
    @Autowired
    private DocTitleMapper docTitleMapper;
    @Autowired
    private DocContentParagraphMapper docContentParagraphMapper;
    @Autowired
    private DocContentTableMapper docContentTableMapper;
    @Autowired
    private DocAppendixMapper docAppendixMapper;
    @Autowired
    private DocAppendixParagraphMapper docAppendixParagraphMapper;
    @Autowired
    private DocAppendixSubMapper docAppendixSubMapper;
    @Autowired
    private DocOperationSheetStyleMapper docOperationSheetStyleMapper;
    @Autowired
    private DocParagraphSubMapper docParagraphSubMapper;
    @Autowired
    private ICommonFileManager iCommonFileService;
    @Autowired
    private DrawConf drawConf;


    /***
     * 实现数据的查询
     * @param docId
     * @param tableSize
     * @return
     */
    @Override
    public DocResult getDocResultService(Long docId, Integer tableSize) {
        DocResult docResult = new DocResult();
        // 记录文档的页数
        int pages = 0;
        // 查询Doc文档主信息
        DocIndex docIndex = docIndexMapper.selectById(docId);
        docResult.setDocIndex(docIndex);
        pages++;

        // 查询Doc文件的审批信息
        QueryWrapper docApprovalWrapper = new QueryWrapper();
        docApprovalWrapper.eq("doc_index_id", docId);
        DocApproval docApproval = docApprovalMapper.selectOne(docApprovalWrapper);
        docResult.setDocApproval(docApproval);


        // 查询版本变更记录
        QueryWrapper docRevWrapper = new QueryWrapper();
        docRevWrapper.eq("doc_index_id", docId);
        List<DocRev> docRevs = docRevMapper.selectList(docRevWrapper);
        docResult.setDocRevList(docRevs);
        pages++;

        // 查询标题内容
        QueryWrapper docTitleWrapper = new QueryWrapper();
        docTitleWrapper.eq("doc_index_id", docId);
        docTitleWrapper.orderByAsc("step_num");
        List<DocTitle> docTitleList = docTitleMapper.selectList(docTitleWrapper);
        List<DocParagraphTable> list = new ArrayList<>();
        pages++;

        List<DocParagraphTable> paragraphList = new ArrayList<>();
        // 处理附录数据
        DocAppendixTitleDto datd = new DocAppendixTitleDto();

        int fla = 1;
        // 遍历标题查询所有内容
        for(DocTitle dt : docTitleList){

            Integer titleType = dt.getTitleType();
            String tId = dt.getId();
            boolean flag = true;

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("doc_title_id", tId);
            queryWrapper.orderByAsc("step_num");
            DocParagraphTable dpt = new DocParagraphTable();
            dpt.setDocTitle(dt);
            switch (titleType){
                // 处理段落数据
                case 0:
                    List list2 = docContentParagraphMapper.selectList(queryWrapper);
                    dpt.setDocContentList(getParagraph(list2));
                    pages++;
                    list.add(dpt);
                    break;
                // 处理表格数据
                case 1:
                    List result = new ArrayList();
                    List list4 = docContentTableMapper.selectList(queryWrapper);
                    List list3 = handleContentParagraph(list4);
                    if(list3.size()<=tableSize){
                        result.add(list3);
                        pages++;
                    }else{
                        int mod = 0;
                        int i;
                        List subList = new ArrayList();
                        for(i=0; i< list3.size(); i++){
                            if (Math.abs(i/tableSize)==mod){
                                subList.add(list3.get(i));
                            }else{
                                mod = i/tableSize;
                                result.add(subList);
                                pages++;
                                subList = new ArrayList();
                                subList.add(list3.get(i));
                            }
                        }
                        if(i==list3.size()){
                            // 如果为空，则返回true
                            if (isEmptyList(subList)){
                                flag = false;
                            }
                            if(flag){
                                result.add(subList);
                                pages++;
                            }
                            flag = true;
                        }
                    }
                    dpt.setDocContentList(result);
                    list.add(dpt);
                    break;
                // 处理附录表格数据
                case 2:
                    // 查询标题下的数据
                    QueryWrapper wrapper = new QueryWrapper();
                    wrapper.in("doc_title_id", tId);
                    wrapper.orderByAsc("page_flag");
                    wrapper.orderByAsc("step_num");
                    List<DocAppendix> selList = docAppendixMapper.selectList(wrapper);
                    List<DocAppendix> list1 = handleAppendixTitleParagraph(selList);
                    List<DocAppendix> res = new ArrayList<>();
                    int i;
                    for(i=0; i<list1.size(); i++){
                        DocAppendix da = list1.get(i);
                        if(da.getPageFlag()==fla){
                            res.add(da);
                        }else{
                            fla = da.getPageFlag();
                            if(res.size()>0){
                                List<JSONArray> appendixTable = getAppendixTable(res);
                                DocParagraphTable dpt2 = new DocParagraphTable();
                                dpt2.setDocTitle(dt);
                                dpt2.setDocContentList(appendixTable);
                                paragraphList.add(dpt2);
                                pages++;
                            }
                            res = new ArrayList<>();
                            res.add(da);
                        }
                    }
                    List<JSONArray> appendixTable = getAppendixTable(res);
                    dpt.setDocContentList(appendixTable);
                    paragraphList.add(dpt);
                    fla ++;
                    pages++;
                    break;
                // 处理附录段落数据
                case 3:

                    List<DocAppendixParagraph> appendixParagraphList = docAppendixParagraphMapper.selectList(queryWrapper);

                    for(DocAppendixParagraph dap : appendixParagraphList){
                        Integer conType = dap.getConType();
                        if(conType==1){
                            QueryWrapper query = new QueryWrapper();
                            query.eq("doc_appendix_paragraph_id", dap.getId());
                            // 查询子表数据
                            dap.setDocAppendixSubList(docAppendixSubMapper.selectList(query));
                        }
                    }
                    dpt.setDocParagraphList(appendixParagraphList);
                    pages++;
                    paragraphList.add(dpt);
                    break;
                // 处理附录标题数据
                case 4:
                    datd.setDocTitle(dt);
                    break;
                // 处理操作单
                case 5:
                    QueryWrapper query = new QueryWrapper();
                    query.eq("doc_title_id", tId);
                    List operation = getOperation(docOperationSheetStyleMapper.selectList(query));
                    docResult.setDocOperationSheetStyleList(operation);
                    pages++;
                default:
                    System.out.println("暂无该段落类型2222");
                    break;
            }
        }

        datd.setDocAppendixDataList(paragraphList);
        docResult.setDocAppendix(datd);
        docResult.setDocTitleContentList(list);
        docResult.setDocTitleMenuList(getMenuList(docTitleList));

        docResult.setPagesSum(pages);
        return docResult;
    }

    /***
     * 实现表格数据的处理
     * @param list
     * @return
     */
    public List<DocContentTable> handleContentParagraph(List<DocContentTable> list){
        Iterator<DocContentTable> iterator = list.iterator();
        while (iterator.hasNext()){
            DocContentTable d = iterator.next();
            if(d.getRowType()==5) {
                String tId = d.getId();
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.in("doc_title_id", tId);
                queryWrapper.orderByAsc("step_num");
                List list1 = docContentParagraphMapper.selectList(queryWrapper);
                if(list1.size()>0){
                    d.setTableParagraphList(list1);
                }else{
                    iterator.remove();
                }
            }
        }
//        for (DocContentTable d: list){
//            if(d.getRowType()==5) {
//                String tId = d.getId();
//                QueryWrapper queryWrapper = new QueryWrapper();
//                queryWrapper.in("doc_title_id", tId);
//                queryWrapper.orderByAsc("step_num");
//                List list1 = docContentParagraphMapper.selectList(queryWrapper);
//                if(list1.size()>0){
//                    d.setTableParagraphList(list1);
//                }else{
//                    list.remove
//                }
//            }
//        }
        return list;
    }

    /****
     *
     * @param list
     * @return
     */
    public List<DocAppendix> handleAppendixTitleParagraph(List<DocAppendix> list){
        Iterator<DocAppendix> iterator = list.iterator();
        while (iterator.hasNext()){
            DocAppendix d = iterator.next();
            if(d.getRowType()==5) {
                String tId = d.getId();
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.in("doc_title_id", tId);
                queryWrapper.orderByAsc("step_num");
                List list1 = docAppendixParagraphMapper.selectList(queryWrapper);
                if(list1.size()>0){
                    d.setAppendixList(list1);
                }else{
                    iterator.remove();
                }
            }
        }
//        for (DocContentTable d: list){
//            if(d.getRowType()==5) {
//                String tId = d.getId();
//                QueryWrapper queryWrapper = new QueryWrapper();
//                queryWrapper.in("doc_title_id", tId);
//                queryWrapper.orderByAsc("step_num");
//                List list1 = docContentParagraphMapper.selectList(queryWrapper);
//                if(list1.size()>0){
//                    d.setTableParagraphList(list1);
//                }else{
//                    list.remove
//                }
//            }
//        }
        return list;
    }
 /*   @Override
    public DocResult getDocResultService(Long docId, Integer tableSize, Integer apTabSize) {
        DocResult docResult = new DocResult();
        // 记录文档的页数
        int pages = 0;
        // 查询Doc文档主信息
        DocIndex docIndex = docIndexMapper.selectById(docId);
        docResult.setDocIndex(docIndex);
        pages++;

        // 查询Doc文件的审批信息
        QueryWrapper docApprovalWrapper = new QueryWrapper();
        docApprovalWrapper.eq("doc_index_id", docId);
        DocApproval docApproval = docApprovalMapper.selectOne(docApprovalWrapper);
        docResult.setDocApproval(docApproval);


        // 查询版本变更记录
        QueryWrapper docRevWrapper = new QueryWrapper();
        docRevWrapper.eq("doc_index_id", docId);
        List<DocRev> docRevs = docRevMapper.selectList(docRevWrapper);
        docResult.setDocRevList(docRevs);
        pages++;

        // 查询标题内容
        QueryWrapper docTitleWrapper = new QueryWrapper();
        docTitleWrapper.eq("doc_index_id", docId);
        List<DocTitle> docTitleList = docTitleMapper.selectList(docTitleWrapper);
        List<DocParagraphTable> list = new ArrayList<>();
        pages++;

        List<DocParagraphTable> paragraphList = new ArrayList<>();
        // 处理附录数据
        DocAppendixTitleDto datd = new DocAppendixTitleDto();

        // 遍历标题查询所有内容
        for(DocTitle dt : docTitleList){

            Integer titleType = dt.getTitleType();
            Long tId = dt.getId();
            boolean flag = true;

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("doc_title_id", tId);
            DocParagraphTable dpt = new DocParagraphTable();
            dpt.setDocTitle(dt);
            switch (titleType){
                // 处理段落数据
                case 0:
                    List list2 = docContentParagraphMapper.selectList(queryWrapper);
                    dpt.setDocContentList(list2);
                    pages++;
                    list.add(dpt);
                    break;
                // 处理表格数据
                case 1:
                    List result = new ArrayList();
                    List list3 = docContentTableMapper.selectList(queryWrapper);
                    if(list3.size()<=tableSize){
                        result.add(list3);
                        pages++;
                    }else{
                        int mod = 0;
                        int i;
                        List subList = new ArrayList();
                        for(i=0; i< list3.size(); i++){
                            if (Math.abs(i/tableSize)==mod){
                                subList.add(list3.get(i));
                            }else{
                                mod = i/tableSize;
                                result.add(subList);
                                pages++;
                                subList = new ArrayList();
                                subList.add(list3.get(i));
                            }
                        }
                        if(i==list3.size()){
                            if (subList.size()==1){
                                DocContentTable o = (DocContentTable) subList.get(0);
                                if ("{}".equals(o.toString())){
                                    flag = false;
                                }
                            }
                            if(flag){
                                result.add(subList);
                                pages++;
                            }
                        }
                    }
                    dpt.setDocContentList(result);
                    list.add(dpt);
                    break;
                // 处理附录表格数据
                case 2:
                    // 查询标题下的数据
                    List<DocAppendix> list1 = docAppendixMapper.selectList(queryWrapper);
                    if(apTabSize>1 && list1.size()>apTabSize) {
                        int mod = 0;
                        int i;
                        List subList = new ArrayList();
                        for(i=0; i< list1.size(); i++){
                            if (Math.abs(i/apTabSize)==mod){
                                subList.add(list1.get(i));
                            }else{
                                mod = i/apTabSize;
                                List<JSONArray> appendixTable = getAppendixTable(subList);
                                DocParagraphTable dpt2 = new DocParagraphTable();
                                dpt2.setDocTitle(dt);
                                dpt2.setDocContentList(appendixTable);
                                paragraphList.add(dpt2);
                                pages++;
                                subList = new ArrayList();
                                subList.add(list1.get(i));
                            }
                        }
                        if(i==list1.size()){
                            if (subList.size()==1){
                                DocAppendix o = (DocAppendix) subList.get(0);
                                if ("{}".equals(o.toString())){
                                    flag = false;
                                }
                            }
                            if(flag){
                                List<JSONArray> appendixTable = getAppendixTable(subList);
                                DocParagraphTable dpt2 = new DocParagraphTable();
                                dpt2.setDocTitle(dt);
                                dpt2.setDocContentList(appendixTable);
                                paragraphList.add(dpt2);
                                pages++;
                            }
                        }
                        break;
                    }
                    List<JSONArray> appendixTable = getAppendixTable(list1);
                    dpt.setDocContentList(appendixTable);
                    paragraphList.add(dpt);
                    break;
                // 处理附录段落数据
                case 3:
                    List<DocAppendixParagraph> appendixParagraphList = docAppendixParagraphMapper.selectList(queryWrapper);

                    for(DocAppendixParagraph dap : appendixParagraphList){
                        Long conType = dap.getConType();
                        if(conType==1L){
                            QueryWrapper query = new QueryWrapper();
                            query.eq("doc_appendix_paragraph_id", dap.getId());
                            // 查询子表数据
                            dap.setDocAppendixSubList(docAppendixSubMapper.selectList(query));
                        }
                    }
                    dpt.setDocParagraphList(appendixParagraphList);
                    pages++;
                    paragraphList.add(dpt);
                    break;
                // 处理附录标题数据
                case 4:
                    datd.setDocTitle(dt);
                    break;
                // 处理操作单
                case 5:
                    QueryWrapper query = new QueryWrapper();
                    query.eq("doc_title_id", tId);
                    List operation = getOperation(docOperationSheetStyleMapper.selectList(query));
                    docResult.setDocOperationSheetStyleList(operation);
                    pages++;
                default:
                    System.out.println("暂无该段落类型");
                    break;
            }
        }

        datd.setDocAppendixDataList(paragraphList);
        docResult.setDocAppendix(datd);
        docResult.setDocTitleContentList(list);
        docResult.setDocTitleMenuList(getMenuList(docTitleList));

        docResult.setPagesSum(pages);
//        System.out.println(pages++);
        return docResult;
    }*/

    /***
     * 实现数据的删除
     * @param docId
     * @return
     */
    @Override
    public int removeDocDataService(Long docId) {
        // 删除索引信息
        docIndexMapper.deleteById(docId);
        // 删除审批表中的数据
       QueryWrapper wrapper = new QueryWrapper();
       wrapper.eq("doc_index_id", docId);
        docApprovalMapper.delete(wrapper);
        // 删除版本修改历史中的数据
        docRevMapper.delete(wrapper);
        // 删除标题表中的数据
        List<DocTitle> list = docTitleMapper.selectList(wrapper);
        // 删除子表中的数据
        for(DocTitle dt: list){
            QueryWrapper wp = new QueryWrapper();
            wp.eq("doc_title_id", dt.getId());
            Integer titleType = dt.getTitleType();
            switch (titleType){
                // 删除段落数据
                case 0:
                    docContentParagraphMapper.delete(wp);
                    break;
                // 删除内容表格数据
                case 1:
                    docContentTableMapper.delete(wp);
                    break;
                // 删除附录表格数据
                case 2:
                    docAppendixMapper.delete(wp);
                    break;
                // 删除附录段落数据
                case 3:
                    docAppendixParagraphMapper.delete(wp);
                    break;
                default:
                    break;
            }
        }
        docTitleMapper.delete(wrapper);
        return 1;
    }

    /****
     * 实现公式数据的修改
     * @param flag 表示的数据位置
     * @param pid 修改的id
     * @param data 数据
     * @param index 位置
     * @return
     */
    @Override
    public int saveFormulaService(int flag, String pid, String data, int index) throws Exception {
        int i=0;
//        // 实现数据解码
///        data = URLDecoder.decode(data, "UTF-8");
        switch (flag){
            // 正文段落
            case 0:
                DocContentParagraph docContentParagraph = docContentParagraphMapper.selectById(pid);
                JSONObject contentStyle1 = docContentParagraph.getContentStyle();
                docContentParagraph.setContentStyle((JSONObject) JSON.toJSON(updateFormula(contentStyle1, data, index)));
                 i = docContentParagraphMapper.updateById(docContentParagraph);
                break;
            // 正文表格
            case 1:
                break;
            // 附录段落
            case 3:
                DocAppendixParagraph docAppendixParagraph = docAppendixParagraphMapper.selectById(pid);
                JSONObject contentStyle = docAppendixParagraph.getContentStyle();
                docAppendixParagraph.setContentStyle((JSONObject) JSON.toJSON(updateFormula(contentStyle, data, index)));
                i = docAppendixParagraphMapper.updateById(docAppendixParagraph);
                break;
            // 附录表格
            case 2:

                break;
            default:
                System.out.println("请联系管理员处理");
                break;
        }
        return i;
    }

    @Override
    public VueVisioDto uploadVisioService(MultipartFile file, int flag, String pid, int index) throws Exception {
        // 实现文件上传
        String[] allowedExtension = {"vsd", "vsdx"};
        CommonFile commonFile = iCommonFileService.upload(file, allowedExtension);
        // 获取服务器上的文件地址
        String fileType = commonFile.getFileExt();
        String type = "/" + fileType;
        String filePath = drawConf.getFileDir() + commonFile.getDownloadUrl().substring(commonFile.getDownloadUrl().indexOf(type));
        String toImgPath = filePath.replace("." + fileType, ".png");
        String template = "D:/template/" + commonFile.getFileRealName();
        /**** 实现Visio文件转为png文件，将png文件路径返回*/

        FileUtil.copyFile(new File(filePath), new File(template));
        String imgAddress = PdfToPngUtil.visioToPng(template);
        FileUtil.copyFile(new File(imgAddress), new File(toImgPath));
        TextInfo textInfo = new TextInfo();

        filePath = "/profile" + filePath.substring(filePath.indexOf(type));
        toImgPath = "/profile" +  toImgPath.substring(toImgPath.indexOf(type));
        /*****/
        /**** 实现数据库数据修改  ***/
        switch (flag){
            // 正文段落
            case 0:
                DocContentParagraph docContentParagraph = docContentParagraphMapper.selectById(pid);
                JSONObject contentStyle1 = docContentParagraph.getContentStyle();
                Map<String, Object> map1 = updateVisio(contentStyle1, filePath, toImgPath, index);
                textInfo = (TextInfo) map1.get("textInfo");
                docContentParagraph.setContentStyle((JSONObject) JSON.toJSON(map1.get("paragraphTextStyle")));
                docContentParagraphMapper.updateById(docContentParagraph);
                break;
            // 正文表格
            case 1:
                break;
            // 附录表格
            case 2:

                break;
            // 附录段落
            case 3:
                DocAppendixParagraph docAppendixParagraph = docAppendixParagraphMapper.selectById(pid);
                JSONObject contentStyle = docAppendixParagraph.getContentStyle();
                Map<String, Object> map = updateVisio(contentStyle, filePath, toImgPath, index);
                textInfo = (TextInfo) map.get("textInfo");
                docAppendixParagraph.setContentStyle((JSONObject) JSON.toJSON(map.get("paragraphTextStyle")));
                docAppendixParagraphMapper.updateById(docAppendixParagraph);
                break;
            default:
                System.out.println("请联系管理员处理");
                break;
        }
        /********/
        VueVisioDto visioDto = new VueVisioDto();
        visioDto.setVisioPath(filePath);
        visioDto.setImgPath(toImgPath);
        visioDto.setImgHeight(textInfo.getImgHeight());
        visioDto.setImgWidth(textInfo.getImgWidth());
        return visioDto;
    }

    /***
     * 修改公式数据
     * @param contentStyle
     * @param data
     * @param index
     * @return
     */
    public ParagraphTextStyle updateFormula(JSONObject contentStyle, String data, int index){
        ParagraphTextStyle paragraphTextStyle = contentStyle.toJavaObject(ParagraphTextStyle.class);
        List<TextInfo> textInfoList = paragraphTextStyle.getTextInfoList();
        TextInfo textInfo = textInfoList.get(index);
        textInfo.setFormula(data);
        return paragraphTextStyle;
    }

    /***
     * 实现Visio文件数据的修改
     * @param contentStyle
     * @param visioAddress
     * @param imgAddress
     * @param index
     * @return
     */
    public Map<String, Object> updateVisio(JSONObject contentStyle, String visioAddress, String imgAddress, int index){
        Map<String, Object> map = new HashMap<>();
        ParagraphTextStyle paragraphTextStyle = contentStyle.toJavaObject(ParagraphTextStyle.class);
        List<TextInfo> textInfoList = paragraphTextStyle.getTextInfoList();
        TextInfo textInfo = textInfoList.get(index);
        textInfo.setImgAddress(imgAddress);
        textInfo.setVisioAddress(visioAddress);

        map.put("textInfo", textInfo);
        map.put("paragraphTextStyle", paragraphTextStyle);
        return map;
    }
    /***
     * 将附录中的每个对象进行分表
     * @param list1
     * @return
     */
    private List<JSONArray> getAppendixTable(List<DocAppendix> list1){

        List<JSONArray> result = new ArrayList<>();
        List<DocAppendix> appendixList = new ArrayList<>();
        Integer tabFlag = 0;
        for(DocAppendix da: list1){
            if(da.getTabFlag()!=null){
                if(!tabFlag.equals(da.getTabFlag())){
                    if(appendixList.size()>0){
                        result.add((JSONArray) JSON.toJSON(appendixList));
                    }
                    appendixList = new ArrayList<>();
                    tabFlag = da.getTabFlag();
                }

                appendixList.add(da);
            }
        }
        if(appendixList.size()>0){
            result.add((JSONArray) JSON.toJSON(appendixList));
        }

        return result;
    }

    /***
     *  获取目录菜单
     * @param docTitleList
     * @return
     */
    private List<DocTitleDto> getMenuList(List<DocTitle> docTitleList) {

        // 记录所有的标题数据
        List<DocTitleDto> docTitleMenuList = new ArrayList<>();

        // 处理附录的二级标题
        List<TitleLevelDto> twoAppTitleList = new ArrayList<>();
        List<String> appTwoTitleNameList = new ArrayList<>();
        // 处理附录数据
        DocTitleDto appMenu = new DocTitleDto();
        for (DocTitle dt : docTitleList) {
            Integer titleType = dt.getTitleType();
            String tId = dt.getId();
            String titleName = dt.getTitleName();
            if(titleName.startsWith("附录")){
                // 获取处理后的附录标题名称
                String appendixTitleName = getAppendixTitleName(titleName);
                if(!appTwoTitleNameList.contains(appendixTitleName)){
                    TitleLevelDto appTitle = new TitleLevelDto();
                    appTitle.setId(tId);
                    appTitle.setIdentification(3);
                    appTwoTitleNameList.add(appendixTitleName);
                    appTitle.setTitleName(appendixTitleName);
                    twoAppTitleList.add(appTitle);
                }
                continue;
            }
            if(titleName.endsWith("附录")){

                TitleLevelDto oneTitleLevel = new TitleLevelDto();
                oneTitleLevel.setId(tId);
                oneTitleLevel.setTitleName(titleName);
                appMenu.setOneTitle(oneTitleLevel);
                continue;
            }
            // 处理附录数据
            DocTitleDto menu = new DocTitleDto();
            TitleLevelDto oneTitleLevel = new TitleLevelDto();
            oneTitleLevel.setId(tId);
            oneTitleLevel.setTitleName(titleName);
            menu.setOneTitle(oneTitleLevel);
            // 记录二级标题
            List<TitleLevelDto> twoTitleList = new ArrayList<>();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("doc_title_id", tId);
            queryWrapper.orderByAsc("step_num");
            switch (titleType) {
                // 处理段落数据
                case 0:
                    // 处理二级目录
                    queryWrapper.eq("con_type", 1);
                    List<DocContentParagraph> select = docContentParagraphMapper.selectList(queryWrapper);
                    for (DocContentParagraph doc : select) {
                        String content = doc.getContent();
                        if(isOneTitle(content)){
                            TitleLevelDto twoTitleLevel = new TitleLevelDto();
                            twoTitleLevel.setId(doc.getId());
                            twoTitleLevel.setIdentification(0);
                            twoTitleLevel.setTitleName(content);
                            twoTitleList.add(twoTitleLevel);
                        }
                    }
                    menu.setTwoTitleList(twoTitleList);
                    break;
                // 处理表格数据
                case 1:
                    queryWrapper.eq("row_type", 1);
                    List<DocContentTable> listTable = docContentTableMapper.selectList(queryWrapper);
                    for (DocContentTable ta : listTable) {
                        String content = ta.getC1O();
                        if(isOneTitle(content)){
                            TitleLevelDto twoTitleLevel = new TitleLevelDto();
                            twoTitleLevel.setId(ta.getId());
                            twoTitleLevel.setIdentification(1);
                            // 处理内容
                            twoTitleLevel.setTitleName(getTitleName(content));
                            twoTitleList.add(twoTitleLevel); 
                        }
                    }
                    menu.setTwoTitleList(twoTitleList);
                    break;
                default:
                    System.out.println("暂无该段落类型333");
                    break;
            }

            docTitleMenuList.add(menu);
        }
        appMenu.setTwoTitleList(twoAppTitleList);
        if(appMenu.getTwoTitleList()!=null && appMenu.getOneTitle()!=null){
            docTitleMenuList.add(appMenu);
        }
        return docTitleMenuList;
    }

    /**
     * 判断是否为二级标题
     * @param msg
     * @return
     */
    private boolean isOneTitle(String msg){

        String reg = "^\\d+\\.\\d+.*$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(msg);

        return matcher.matches();
    }

    /***
     * 获取标题的内容
     * @param msg
     * @return
     */
    private  String getTitleName(String msg){
        String reg = "\\d+\\.?\\d+\\s{2}\\S*";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(msg);
        String group = "";
        if (matcher.find()){
            group = matcher.group();
        }
        return group;
    }

    /***
     * 处理附录的二级标题内容
     * @param msg
     * @return
     */
    private String getAppendixTitleName(String msg){
        // 判断括号是不是在后边
        if(msg.lastIndexOf("）")>msg.length()-3 || msg.lastIndexOf(")")>msg.length()-3 ){
            if (msg.contains("（")){
                msg = msg.substring(0, msg.lastIndexOf("（"));
            }else if(msg.contains("(")){
                msg = msg.substring(0, msg.lastIndexOf("("));
            }
        }

        return msg;
    }

    /**
     * 实现分表
     * @param list
     * @return
     */
    private List<JSONArray> getOperation(List<DocOperationSheetStyle> list){
        List<JSONArray> result = new ArrayList<>();
        List<DocOperationSheetStyle> mid = new ArrayList<>();
        Integer index = 0;

        for(DocOperationSheetStyle dos : list){

            if(dos.getRowType()!=null){
                if(!index.equals(dos.getRowType())){
                    if(mid.size()>0){
                        result.add((JSONArray) JSON.toJSON(mid));
                    }
                    mid = new ArrayList<>();
                    index = dos.getRowType();
                }

                mid.add(dos);
            }
        }
        if(mid.size()>0){
            result.add((JSONArray) JSON.toJSON(mid));
        }
        return result;
    }

    /***
     * 实现数据段落数据子表的查询
     * @param list
     * @return
     */
    private List getParagraph(List<DocContentParagraph> list){
        for (DocContentParagraph doc: list){
            if (doc.getConType()==3){
                QueryWrapper query = new QueryWrapper();
                query.eq("doc_paragraph_id", doc.getId());
                // 查询子表数据
                doc.setDocParagraphSubList(docParagraphSubMapper.selectList(query));
            }
        }
        return list;
    }

    /***
     * 判断集合是不是全为空
     * @param list
     * @return
     */
    private boolean isEmptyList(List<DocContentTable> list){
        for (DocContentTable d: list){
            if (!"{}".equals(d.toString())){
                return false;
            }
        }
        return true;
    }

}
